<script setup>
import {ref, watch} from 'vue'
import {Search} from '@element-plus/icons-vue'
import {defineProps} from "vue"
import {isPermission} from "../../utils/utils.js";
import {deleteResource, listResource} from "../../api/course/course.js";
import UploadResource from "./Mangement/UploadResource.vue";
import {ElMessage} from "element-plus";
const prop = defineProps(['courseId'])


// 显示上传弹窗
const isUpload=ref(false)
// 关闭弹窗
const handleClose=()=>{
  isUpload.value=false;
}

const multipleTableRef = ref();
// 显示下载按钮
const displayDownload = ref(false);
// 资源数组
const resource = ref([]);

// 资源图标
const resourceIcon =['https://iflytek-education.oss-cn-beijing.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20240711213737.jpg','https://iflytek-education.oss-cn-beijing.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20240711213732.jpg'];

const condition=ref({
  resourceName:''
});

const resourceName = ref('');

// 显示下载按钮
const handleDisplayDownload = (val) => {
  multipleTableRef.value = val;
  console.log(multipleTableRef.value);
  displayDownload.value = multipleTableRef.value.length > 0;
}

// 搜索资源
const handleListResource = async () => {
  condition.value['resourceName']=resourceName.value;
  console.log(condition.value);
  await listResource(prop.courseId,condition.value).then(res => {
    resource.value=res.data;
    for( let i=0;i<resource.value.length;i++){
      resource.value[i].createTime=new Date(resource.value[i].createTime).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true }).replace('上午', 'AM').replace('下午', 'PM').replace('AM', '上午').replace('PM', '下午')
    }
    console.log(resource.value);
  })
}
// 删除资源
const handleDeleteResource = async () => {
  // 获取id数组
  const ids=multipleTableRef.value.map(item=>item.id);
  await deleteResource(ids).then(res=>{
    ElMessage.success("删除成功");
    handleListResource();
  })
}

// 上传资源
const handleDisplayUpload = () => {
  isUpload.value=true;
  console.log(isUpload.value);
}


// 下载文件
const handleDownload=async()=>{
  for(let i=0;i<multipleTableRef.value.length;i++){
    // 获取下载地址
    const url=multipleTableRef.value[i].link;
    // 使用Fetch API从服务器请求文件资源
    const response = await fetch(url);
    // 将响应体转换成Blob对象，Blob对象表示一个不可变、原始数据的类文件对象
    const blob = await response.blob();
    // 创建一个新的<a>标签元素，用于触发文件下载
    const link = document.createElement('a');
    // 设置<a>元素的href属性，使用URL.createObjectURL()方法创建一个指向Blob对象的URL
    link.href = URL.createObjectURL(blob);
    // 设置<a>元素的download属性，用于指定下载的文件名，留空则使用服务器返回的文件名
    // 注意：可以指定一个文件名，例如：'my-file.pdf'
    link.setAttribute('download', '');
    // 将创建的<a>元素添加到DOM树中，这样就可以触发点击事件
    document.body.appendChild(link);
    // 触发<a>元素的点击事件，从而开始文件下载
    link.click();
    // 移除之前添加的<a>元素，保持页面干净
    document.body.removeChild(link);
    // 当下载完成后，释放由createObjectURL创建的URL对象所占用的内存
    // 这是必要的，否则可能导致内存泄漏
    URL.revokeObjectURL(link.href);
  }
}


handleListResource();
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header style="height: 60px">
        <div style="margin: 20px 0; display: flex; align-items: center; justify-content: space-between;">
          <el-button type="primary" style="margin-right: 20px" v-if="displayDownload" @click="handleDownload">下载文件</el-button>
          <el-button type="danger" v-if="displayDownload&&isPermission(2)" @click="handleDeleteResource">删除资源</el-button>
          <div style="margin-left: auto">
            <el-button type="primary" style="margin-right: 20px" @click="handleDisplayUpload" v-if="isPermission(2)">上传资源</el-button>
            <el-input
                v-model="resourceName"
                style="width: 240px;"
                size="large"
                placeholder="搜索"
                :suffix-icon="Search"
                @keyup.enter="handleListResource"
            />
          </div>
        </div>
      </el-header>
      <el-main style="height: 60vh;">
        <el-table
            ref="multipleTableRef"
            :data="resource"
            style="width: 100%"
            @selection-change="handleDisplayDownload"
            :row-style="{height: '80px'}"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column property="name" width="70">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <img :src="resourceIcon[scope.row.type]" style="width: 40px; height: 40px">
              </div>
            </template>
          </el-table-column>
          <el-table-column property="name" label="文件名"  width="700"></el-table-column>
          <el-table-column property="size" label="大小" />
<!--          <el-table-column property="name" label="创建者"/>-->
          <el-table-column property="createTime" label="创建时间"/>
        </el-table>
      </el-main>
      <UploadResource v-model="isUpload" @close="handleClose" @search="handleListResource"></UploadResource>
    </el-container>
  </div>
</template>


<style scoped lang="less">
.resource-img {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  border-radius: 2px;
}
</style>